package com.eunion.web.admin.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eunion.core.LogUtil;
import com.eunion.core.PageData;
import com.eunion.core.common.DeleteVo;
import com.eunion.core.common.JsonVo;
import com.eunion.core.common.KvVo;
import com.eunion.core.exception.ValidateException;
import com.eunion.web.admin.entity.AdminAuth;
import com.eunion.web.admin.service.AdminAuthService;
import com.eunion.web.common.base.BaseService;
import com.eunion.web.common.base.BaseTableCommonController;
import com.eunion.web.common.vo.Web;
import com.eunion.common.util.CommUtils;

/**
 * 权限.
 *
 * @since 2016年12月20日
 */
@Scope("prototype")
@Controller
@RequestMapping(value = "/admin/adminauth")
@PreAuthorize("hasAuthority('admin:auth:main')")
public class AdminAuthController extends BaseTableCommonController<AdminAuth, String> {
 
 // @RequiresPermissions("admin:auth:main")
 @Override
 @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
 public String main(PageData<AdminAuth> pages, Model model) {
  // Subject currentUser = SecurityUtils.getSubject();
  // currentUser.checkPermission("admin:auth");
  setModuleQuery(model);
  model.addAttribute("pages", pages);
  return getUrlBase();
 }
 
 /**
  * Post 保存对象.
  */
 // @RequiresPermissions("admin:auth:add")
 @PreAuthorize("hasAuthority('admin:auth:add')")
 @RequestMapping(value = Web.URL_SEP_SAVE, method = {RequestMethod.POST})
 private String save(@Valid AdminAuth obj, BindingResult result, Model model) {
  try {
   setAuthList(model);
   checkBindResult(result);// 检查bindingresult中是否有异常.
   
   List<AdminAuth> objDb = adminAuthService.findByAuthCodeOrAuthName(obj.getAuthCode(), obj.getAuthName());
   if (objDb != null && objDb.size() > 0) {
    setModuleAdd(model);
    setModuleStatusError(model, "权限代码或名字已存在!");
    model.addAttribute(Web.OBJ, obj);
    return getUrlBase().concat("-add");
   }
   // 检查父级代码是否存在
   if (!obj.getParentAuthCode().equals("ROOT")) {
    AdminAuth parent = adminAuthService.findOne(obj.getParentAuthCode());
    if (parent == null) {
     model.addAttribute(Web.OBJ, obj);
     throw new ValidateException("请选择合法的父级权限");
    }
   }
   obj.setCreatedTime(CommUtils.getDayTimestamp());
   setModuleStatusOK(model);
   getBaseService().save(obj);
   // model.addAttribute(Web.OBJ, new AdminAuth());
   setModuleStatusOK(model, "新增成功");
  } catch (ValidateException ve) {
   model.addAttribute(Web.OBJ, obj);
   setModuleStatusError(model, ve.getMsg());
  } catch (Exception e) {
   model.addAttribute(Web.OBJ, obj);
   LogUtil.get(this.getClass()).error("save obj error : {}", e);
   setModuleStatusError(model, "新增失败");
  }
  setModuleAdd(model);
  return getUrlBase().concat("-add");
 }
 
 /**
  * 添加权限列表
  */
 private void setAuthList(Model model) {
  if (adminAuthService == null) {
      // adminAuthService为null，需要重新获取。
      adminAuthService = (AdminAuthService)getBaseService();
  }
  List<KvVo> authlist = adminAuthService.findAllAuths();
  model.addAttribute("authlist", authlist);
 }
 
 // @RequiresPermissions("admin:auth:add")
 @Override
 @RequestMapping(value = Web.URL_SEP_ADD, method = RequestMethod.GET)
 @PreAuthorize("hasAuthority('admin:auth:add')")
 protected String add(Model model) {
  setModuleAdd(model);
  setAuthList(model);
  model.addAttribute(Web.OBJ, getT());
  return getUrlBase().concat("-add");
 }
 
 // @RequiresPermissions("admin:auth:edit")
 @Override
 @RequestMapping(value = Web.URL_SEP_EDIT + "/{id}", method = RequestMethod.GET)
 @PreAuthorize("hasAuthority('admin:auth:edit')")
 protected String edit(@PathVariable String id, Model model) {
  setModuleEdit(model);
  setAuthList(model);
  AdminAuth objDb = getBaseService().findOne(id);
  model.addAttribute(Web.OBJ, objDb);
  return getUrlBase().concat("-edit");
 }
 
 /**
  * Post 更新对象.
  */
 // @RequiresPermissions("admin:auth:edit")
 @RequestMapping(value = Web.URL_SEP_UPDATE, method = {RequestMethod.POST})
 @PreAuthorize("hasAuthority('admin:auth:edit')")
 private String update(@Valid AdminAuth obj, BindingResult result, Model model) {
  try {
   setModuleEdit(model);
   setAuthList(model);
   model.addAttribute(Web.OBJ, obj);
   checkBindResult(result);// 检查bindingresult中是否有异常.
   AdminAuth objDb = adminAuthService.findOne(obj.getAuthCode());
   if (objDb == null) {
    setModuleAdd(model);
    setModuleStatusError(model, "权限不存在!");
    return getUrlBase().concat("-edit");
   }
   objDb.setUpdatedTime(CommUtils.getDayTimestamp());
   // 检查名字是否为唯一
   if (!objDb.getAuthName().equals(obj.getAuthName())) {
    List<AdminAuth> objCheckList = adminAuthService.findByAuthCodeOrAuthName(obj.getAuthCode(), obj.getAuthName());
    if (objCheckList != null && objCheckList.size() > 1) {
     setModuleAdd(model);
     setModuleStatusError(model, "权限名字已存在!");
     return getUrlBase().concat("-edit");
    }
    objDb.setAuthName(obj.getAuthName());
   }
   // 检查父级代码是否存在
   if (!obj.getParentAuthCode().equals("ROOT") && !obj.getParentAuthCode().equals(objDb.getParentAuthCode())) {
    AdminAuth parent = adminAuthService.findOne(obj.getParentAuthCode());
    if (parent == null) {
     throw new ValidateException("请选择合法的父级权限");
    }
    objDb.setParentAuthCode(obj.getParentAuthCode());
   }
   
   objDb.setAuthSeq(obj.getAuthSeq());
   objDb.setAuthType(obj.getAuthType());
   objDb.setAuthUrl(obj.getAuthUrl());
   objDb.setStatus(obj.getStatus());
   setModuleStatusOK(model);
   getBaseService().save(objDb);
   setModuleStatusOK(model, "更新成功");
  } catch (ValidateException ve) {
   setModuleStatusError(model, ve.getMsg());
  } catch (Exception e) {
   LogUtil.get(this.getClass()).error("update obj error : {}", e);
   setModuleStatusError(model, "更新失败");
  }
  model.addAttribute(Web.OBJ, obj);
  return getUrlBase().concat("-edit");
 }
 
 /**
  * 根据传入的数据ids,来删除对象. headers = {"Accept=application/json","Content-type=application/json" } , produces = "application/json"
  */
 @RequestMapping(value = Web.URL_SEP_REMOVE, method = RequestMethod.POST)
 @ResponseBody
 @Override
 @PreAuthorize("hasAuthority('admin:auth:remove')")
 public JsonVo remove(@RequestBody DeleteVo<String> dvo) {
  try {
   if (dvo != null && dvo.getIds() != null && dvo.getIds().size() > 0) {
    // 检查有无被其他角色引用,添加索引后，默认是删除不掉的，可以先这样用者，后面改为批量删除处理
    for (String parentAuthCode : dvo.getIds()) {
     List<AdminAuth> refs = adminAuthService.findByParentAuthCode(parentAuthCode);
     if (refs != null && refs.size() > 0) {
      LogUtil.get(this.getClass()).error("code:{}被引用  ", parentAuthCode);
      return new JsonVo(false, "删除失败，请检查权限下是否有其它子权限。");
     }
    }
    
    return super.remove(dvo);
   }
   return new JsonVo(true);
  } catch (Exception e) {
   LogUtil.get(this.getClass()).error("remove erro ", e);
   return new JsonVo(false, "删除出现异常");
  }
 }
 
 @Override
 protected BaseService<AdminAuth, String> getBaseService() {
  return adminAuthService;
 }
 
 @Override
 protected String getUrlBase() {
  return "admin/authority/auth";
 }
 
 @Resource
 private AdminAuthService adminAuthService;
 
}
